package rpc

import (
	"github.com/gogo/protobuf/proto"
	"leaf/core/conf"
	. "leaf/core/error"
	"leaf/core/gate"
	"leaf/core/log"
	. "leaf/core/msg"
	"leaf/pb"
	"reflect"
)

func Rpc_GetLogicAddr(s interface{}, msg *PMsg) *Error {
	gateAddr := msg.S2C().(*pb.S2C_GateAddr)
	gateAddr.Addr = proto.String(conf.Config.WSAddr)
	return nil
}

func Rpc_SendNotify(s interface{}, msg *PMsg) *Error {
	log.Release("Rpc_SendNotify...")
	requestMsg := msg.C2S().(*pb.C2S_NotifyMsg)
	gid := requestMsg.GetGid()
	if gid == 0 {
		log.Error("Rpc_SendNotify err:gid is zero", "gid is zero")
		return nil
	}

	msgBytes := requestMsg.GetMsg()
	if msgBytes == nil {
		log.Error("Rpc_SendNotify gid:%v err:msgBytes is nil", msgBytes)
		return nil
	}

	msgId := requestMsg.GetMsgId()
	msgType := GetMessageType(uint16(msgId))
	msgData := reflect.New(msgType.Elem()).Interface().(proto.Message)
	if err := proto.Unmarshal(msgBytes, msgData); err != nil {
		log.Error("Rpc_SendNotify gid:%v err:%v", msgBytes, err)
		return nil
	}

	agent := gate.GetAgent(gid)
	if agent == nil {
		log.Error("Rpc_SendNotify gid:%v err:agent not find", gid)
		return nil
	}
	agent.SendMsg(msgData)
	log.Release("Rpc_SendNotify success")
	return nil
}
